package org.flashbrighton.as3bots.views
{
	import Box2D.Dynamics.*;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	import org.flashbrighton.as3bots.events.DeadBotEvent;
	import org.flashbrighton.as3bots.models.*;
	import org.flashbrighton.as3bots.views.ui.ScoreBoard;

	public class GameView extends Sprite
	{
		private var _model:GameModel;
		private var _arena:ArenaView;
		
		
		public function GameView(model:GameModel)
		{
			_model = model;
			//_model.addEventListener(Event.CHANGE, update);
			_model.addEventListener(DeadBotEvent.DEAD, removeBot);
			
			//setDebugDraw();			
		}
		
		
		public function update(e:Event=null):void
		{
			var botView:BotGraphic;
			// Go through body list and update sprite positions/rotations
			//for (var bb:b2Body = _model.world.m_bodyList; bb; bb = bb.m_next)			
			for each (var bb:b2Body in _model.botList)
			{
				botView = _model.botViews[bb];
				botView.x = bb.GetPosition().x;
				botView.y = bb.GetPosition().y;
				botView.rotation = bb.GetAngle() * (180/Math.PI);
				botView.update();
			}
		}
		
		
		public function addViews():void
		{
			var bot:b2Body;			
			var botView:Sprite;
			var botModel:BotModel;
			var wall:b2Body;
			var wallView:Sprite;
			var wallModel:WallModel;
			
			// World view
			_arena = new ArenaView();
			addChild(_arena);
			
			// Bots			
			for each (bot in _model.botList)
			{
				botView = _model.botViews[bot];
				botModel = bot.m_userData as BotModel;
				botView.width = botModel.radius * 2;
				botView.height = botModel.radius * 2;
				
				_arena.addChild(botView);
			}
			
			// Walls
			for each (wall in _model.wallList)
			{
				wallView = _model.wallViews[wall];
				wallModel = wall.m_userData as WallModel;
				wallView.width = wallModel.width;
				wallView.height = wallModel.height;
				wallView.x = wall.GetPosition().x;
				wallView.y = wall.GetPosition().y;
				
				_arena.addChild(wallView);
			}
		}
		
		
		public function setUI():void
		{
			addChild(new ScoreBoard(_model));
			//addChild(new Stats());
		}
		
		
		public function removeBot(e:DeadBotEvent):void
		{
			_arena.removeChild(_model.botViews[e.bot]);
		}
		
		
		private function setDebugDraw():void
		{
			var dbgDraw:b2DebugDraw = new b2DebugDraw();
			var dbgSprite:Sprite = new Sprite();
			addChild(dbgSprite);
			dbgDraw.m_sprite = dbgSprite;
			dbgDraw.m_drawScale = 70.0;
			dbgDraw.m_fillAlpha = 0.0;
			dbgDraw.m_lineThickness = 0.0;
			dbgDraw.m_drawFlags = b2DebugDraw.e_shapeBit;
			//dbgDraw.m_drawFlags = 0xFFFFFFFF;
			_model.world.SetDebugDraw(dbgDraw);			
		}
		
	}
}